package tv.geir.slackspace.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import tv.geir.slackspace.common.CallbackPoint;
import tv.geir.slackspace.common.SlackSpaceException;

/**
 * This class manages multiple socket connections and the process of handing out and returning
 * these sockets to other resources. 
 *  
 * @author geir.pettersen
 *
 */
public class SocketPool {

	private InetAddress address;
	private int port;
	private int minPoolSize;
	private int maxPoolSize;
	private int currentPoolSize;
	
	
	
	private Map<Socket,SocketPoolEntry> usedSocketPool;
	private LinkedList<SocketPoolEntry> socketPool;
	
	private static Log log = LogFactory.getLog( SocketPool.class );
	
	/**
	 * Creates a socket pool
	 * @param address
	 * @param port
	 * @throws IOException
	 */
	public SocketPool( InetAddress address, int port ) throws IOException {
		this.address = address;
		this.port = port;
		
		minPoolSize = 1;
		maxPoolSize = 50;
		
		initPool();
	}
	
	/**
	 * Hands out a connected socket from the pool. The socket will not be handed out to anyone else
	 * before it has been returned using the <code>returnSocket()</code> method.
	 * <p>
	 * If there are no sockets available this thread will block until one is.
	 *
	 * @return a connected socket
	 */
	public synchronized SocketPoolEntry getSocket() {
		/*
		 * Block thread and wait for new sockets to be returned if none 
		 * available
		 */
		while( socketPool.size() == 0 )  {
			log.warn( "Socket pool empty" );
			try {
				wait();
				
			} catch (InterruptedException e) {
				log.error( "Interrupted while sleeping", e );
			}
		}
		
		
		SocketPoolEntry entry = socketPool.poll();
		
		Socket socket = entry.getSocket();
		
		entry.setHandedOut( true ) ;
		
		usedSocketPool.put( socket, entry );
		
		log.debug( "Socket " + entry + " handed out from pool" );
		log.debug( socketPool.size() + " sockets are left in pool" );
		return entry;
	}
	
	
	/**
	 * Puts a socket back in the pool.
	 * @param s
	 */
	public synchronized void returnSocket( SocketPoolEntry entry ) {
		
		if( entry != null ) {
			entry.setHandedOut( false );
			socketPool.add( entry );
			notify();
			log.debug( "Socket returned: " + entry.getSocket() + ". " + socketPool.size() + " sockets in pool" );
		}
		else {
			log.warn( "Attemted to return an unmanaged socket or a socket that has already been handed in: " + entry );
		}
	}
	
	private void initPool() throws IOException {
		if( currentPoolSize != 0 ) {
			throw new SlackSpaceException( "pool already initialized" );
		}
		socketPool = new LinkedList<SocketPoolEntry>();
		usedSocketPool = new HashMap<Socket, SocketPoolEntry>();
		currentPoolSize = 0;
		
		while( currentPoolSize++ < minPoolSize ) {
			socketPool.add( newPoolEntry() );			
		}
		if( log.isInfoEnabled() ) {
			log.info( "SocketPool initiated. Pool size=" + socketPool.size() );
		}
	}
	
	private SocketPoolEntry newPoolEntry() throws IOException {
		return new SocketPoolEntry( address, port );
	}
	
	private void writeCallbackInfo( Socket s ) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
			CallbackPoint cp = new CallbackPoint();
			cp.setAddress( null );
			cp.setPort( 1);
			oos.writeObject( cp );
			oos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void disconnect() {
		for( SocketPoolEntry s : socketPool) {
			try {
				s.getSocket().close();
			} catch (IOException e) {
				log.warn( "Error closing socket", e );
			}
		}
	}
	
	class SocketPoolEntry {

		private Socket socket;

		private long connectedTime;

		private int handedOutCount;

		private long handedOutSince;

		private boolean handedOut;
		
		private ObjectOutputStream out = null;
		
		private ObjectInputStream in = null;
		
		public int hashCode() {
			return socket.hashCode();
		}

		public synchronized ObjectOutputStream getOut() throws IOException {
			if( out == null ) {
				out = new ObjectOutputStream( socket.getOutputStream() );
			}
			return out;
		}
		
		
		public synchronized ObjectInputStream getIn() throws IOException {
			if( in == null ) {
				in = new ObjectInputStream( socket.getInputStream() );
			}
			return in;
		}
		public SocketPoolEntry(InetAddress address, int port) throws IOException {
			socket = new Socket(address, port);
			connectedTime = System.currentTimeMillis();
			handedOutCount = 0;
			handedOutSince = -1;
			handedOut = false;
			//writeCallbackInfo( socket );
		}
		
		public long getConnectedTime() {
			return connectedTime;
		}

		public void setConnectedTime(long connectedTime) {
			this.connectedTime = connectedTime;
		}

		public boolean isHandedOut() {
			return handedOut;
		}

		public void setHandedOut(boolean handedOut) {
			this.handedOut = handedOut;
			if( handedOut ) {
				handedOutCount++;
				handedOutSince = System.currentTimeMillis();			
			}
		}

		public int getHandedOutCount() {
			return handedOutCount;
		}

		public long getHandedOutSince() {
			return handedOutSince;
		}


		public Socket getSocket() {
			return socket;
		}

		public void setSocket(Socket socket) {
			this.socket = socket;
		}

		
		
	}
}
